package com.binarysoft.service.common.activiti;

import javax.sql.DataSource;

import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngineConfiguration;

import common.framework.dsb.AbstractServiceBean;
import common.framework.dsb.annotation.DSBService;
import common.framework.dsb.service.ServiceContext;

@DSBService(name = "DSB/ActivitiService", startup = true)
public class ActivitiServiceBean extends AbstractServiceBean implements ActivitiService {

	private ProcessEngine processEngine = null;

	@Override
	public void start(ServiceContext serviceContext) throws Exception {
		super.start(serviceContext);

		serviceContext.loadConfigProperties("activiti.cfg.properties");

		ProcessEngineConfiguration processEngineConfiguration = ProcessEngineConfiguration.createStandaloneProcessEngineConfiguration();
		// config database.
		DataSource dataSource = this.getSqlSessionProvider().getDataSource(serviceContext.getProperty("database_environment").trim());
		processEngineConfiguration.setDataSource(dataSource);
		processEngineConfiguration.setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_FALSE);
		// config engine.
		processEngineConfiguration.setAsyncExecutorEnabled(Boolean.getBoolean(serviceContext.getProperty("asyncExecutorEnabled")));
		processEngineConfiguration.setAsyncExecutorActivate(Boolean.getBoolean(serviceContext.getProperty("asyncExecutorActivate")));
		processEngineConfiguration.setJobExecutorActivate(Boolean.getBoolean(serviceContext.getProperty("jobExecutorActivate")));
		processEngineConfiguration.setActivityFontName(serviceContext.getProperty("activityFontName"));
		processEngineConfiguration.setLabelFontName(serviceContext.getProperty("labelFontName"));
		processEngineConfiguration.setAnnotationFontName(serviceContext.getProperty("annotationFontName"));

		processEngine = processEngineConfiguration.buildProcessEngine();
	}

	@Override
	public ProcessEngine getProcessEngine() throws Exception {
		// TODO Auto-generated method stub
		return processEngine;
	}

	@Override
	public void refresh() throws Exception {
	}

	@Override
	public void close() throws Exception {

		if (processEngine != null) {
			processEngine.close();
		}
	}

}
